package com.ktmall.service.impl;

import com.ktmall.mapper.AddressMapper;
import com.ktmall.pojo.AddressParams;
import com.ktmall.service.AddressService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 地址相关Service实现类
 */
@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;

    @Override
    public int insert(AddressParams address) {
        checkIsDefaultAddress(address);
        return addressMapper.insert(address);
    }

    @Override
    public List<AddressParams> findByUserId(Integer userId) {
        return addressMapper.findByUserId(userId);
    }

    @Override
    public AddressParams findById(Integer id) {
        return addressMapper.findById(id);
    }

    @Override
    public int update(AddressParams address) {
       checkIsDefaultAddress(address);
        return addressMapper.update(address);
    }

    @Override
    public int delById(Integer id) {
        return addressMapper.delById(id);
    }

    private void checkIsDefaultAddress(AddressParams addressParams){
        AddressParams defaultAddress = addressMapper.getDefaultAddress(addressParams.getUserId());
        if (defaultAddress != null && addressParams.getIsDefault() == 1) {
            defaultAddress.setIsDefault(0);
            addressMapper.update(defaultAddress);
        }
    }
}
